from pyramid.config import Configurator
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid_beaker import session_factory_from_settings

from sqlalchemy import engine_from_config

from alpha.modelos import initialize_sql


def main(global_config, **settings):
    """ This function returns a WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    initialize_sql(engine)
    session_factory = session_factory_from_settings(settings)
    authn_policy = AuthTktAuthenticationPolicy(
        'sosecret')
    authz_policy = ACLAuthorizationPolicy()
    config = Configurator(settings=settings,
                          root_factory='alpha.modelos.models.RootFactory',
                          authentication_policy=authn_policy,
                          authorization_policy=authz_policy,
        		  session_factory=session_factory)

    config.add_subscriber('alpha.subscribers.add_base_template',
                          'pyramid.events.BeforeRender')
    config.add_subscriber('alpha.subscribers.csrf_validation',
                          'pyramid.events.NewRequest')

    config.add_static_view('static', 'alpha:static', cache_max_age=3600)

    config.add_route('redirect', '/')
    config.add_route('main', '/main')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_route('usuarios', '/usuarios')
    config.add_route('listar', '/listar')
    config.add_route('listarUsuarios', '/listarUsuarios')


    config.add_view('alpha.vistas.views.redirect', route_name='redirect')
    config.add_view('alpha.vistas.views.listar', route_name='listar')

    config.add_view('alpha.vistas.views.main', route_name='main', 
                    renderer='alpha:templates/main.pt')
    config.add_view('alpha.vistas.views.listarUsuarios', route_name='listarUsuarios', 
                    renderer='alpha:templates/listarUsuarios.pt')
    config.add_view('alpha.vistas.views.usuarios', route_name='usuarios', 
                    renderer='alpha:templates/usuarios.pt', permission='edit')
    config.add_view('alpha.vistas.login.login', route_name='login', 
                    renderer='alpha:templates/login.pt')
    config.add_view('alpha.vistas.login.logout', route_name='logout',permission='edit')
    config.add_view('alpha.vistas.login.login',
                    context='pyramid.httpexceptions.HTTPForbidden',
                    renderer='alpha:templates/login.pt')


    return config.make_wsgi_app()
